/*
 * @Author: 陈德立qq419287484
 * @Date: 2019-02-25 17:16:13
 * @Last Modified by:
 * @Last Modified time: 2019-04-23 11:09:10
 */
import React, { PureComponent } from "react";
import { Tree, message, Button, Row, Col, Input, Popconfirm } from "antd";
import styles from "./Catalogue.less";

const { DirectoryTree } = Tree;
const { TreeNode } = Tree;

const hasKey = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
class Catalogue extends PureComponent {
  state = {
    editingId: null,
  };

  TreeEditable = false;

  componentWillMount() {
    const { editable } = this.props;
    this.TreeEditable = editable;
  }

  runTree = (Data, id) =>
    Data.map((item) => {
      const { editingId } = this.state;
      return hasKey(item, "tenantName") ? (
        <TreeNode
          title={
            this.TreeEditable ? (
              <div>
                {editingId === item.id ? (
                  <Input
                    placeholder="请输入名称，回车保存"
                    onPressEnter={this.editFinish.bind(this, item.id, null)}
                    size="small"
                    style={{ width: "80%" }}
                    defaultValue={item.tenantName}
                    onBlur={this.editCancel}
                  />
                ) : (
                  <Row>
                    <Col
                      className={styles.overflowEllipsis}
                      span={17}
                      title={item.tenantName}
                    >
                      {item.tenantName}
                    </Col>
                    <Col span={7}>{this.editButton(item.id)}</Col>
                  </Row>
                )}
              </div>
            ) : (
              item.tenantName
            )
          }
          key={`tenant|${item.id}`}
          className={styles.treenode}
        >
          {this.runTree(item.apps, item.id)}
        </TreeNode>
      ) : hasKey(item, "appName") ? (
        <TreeNode
          title={
            this.TreeEditable ? (
              <div>
                {editingId === item.id ? (
                  <Input
                    placeholder="请输入名称，回车保存"
                    onPressEnter={this.editFinish.bind(this, item.id, null)}
                    size="small"
                    style={{ width: "80%" }}
                    defaultValue={item.appName}
                    onBlur={this.editCancel}
                  />
                ) : (
                  <Row>
                    <Col
                      className={styles.overflowEllipsis}
                      span={17}
                      title={item.appName}
                    >
                      {item.appName}
                    </Col>
                    <Col span={7}>{this.editButton(item.id)}</Col>
                  </Row>
                )}
              </div>
            ) : (
              item.appName
            )
          }
          key={`app|${item.id}`}
          className={styles.treenode}
        >
          {item.busi ? this.runTree(item.busi, item.id) : null}
        </TreeNode>
      ) : (
        <TreeNode
          title={
            this.TreeEditable ? (
              <div>
                {editingId === `father|${id}|children|${item.id}` ? (
                  <Input
                    placeholder="请输入名称，回车保存"
                    onPressEnter={this.editFinish.bind(this, item.id, "isLeaf")}
                    size="small"
                    style={{ width: "80%" }}
                    defaultValue={item.busiName}
                    onBlur={this.editCancel}
                  />
                ) : (
                  <Row>
                    <Col
                      className={styles.overflowEllipsis}
                      span={17}
                      title={item.busiName}
                    >
                      {item.busiName}
                    </Col>
                    <Col span={7}>
                      {this.editButton(
                        `father|${id}|children|${item.id}`,
                        "isLeaf",
                      )}
                    </Col>
                  </Row>
                )}
              </div>
            ) : (
              item.busiName
            )
          }
          key={`business|father|${id}|children|${item.id}`} // 这是因为父子ID可能会有重复所做的操作
          isLeaf
          className={styles.treenode}
        />
      );
    });

  editButton = (id, isLeaf) => {
    const { appEdit, appDelete, busiEdit, busiDelete } = this.props;
    if (!isLeaf) {
      return (
        <div className={styles.menuIcon}>
          {appEdit && (
            <Button
              shape="circle"
              icon="edit"
              className={styles.edit}
              onClick={this.ondEdit.bind(this, id)}
              ghost
              type="primary"
              size="small"
            />
          )}
          {appDelete && (
            <Popconfirm
              title="确定要删除此项？"
              onConfirm={this.onDelete.bind(this, id, isLeaf)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                shape="circle"
                icon="delete"
                className={styles.delete}
                ghost
                type="primary"
                size="small"
              />
            </Popconfirm>
          )}
        </div>
      );
    }
    return (
      <div className={styles.menuIcon}>
        {busiEdit && (
          <Button
            shape="circle"
            icon="edit"
            className={styles.edit}
            onClick={this.ondEdit.bind(this, id)}
            ghost
            type="primary"
            size="small"
          />
        )}
        {busiDelete && (
          <Popconfirm
            title="确定要删除此项？"
            onConfirm={this.onDelete.bind(this, id, isLeaf)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              shape="circle"
              icon="delete"
              className={styles.delete}
              ghost
              type="primary"
              size="small"
            />
          </Popconfirm>
        )}
      </div>
    );
  };

  ondEdit = (id) => {
    this.setState({
      editingId: id,
    });
  };

  editFinish = (id, isLeaf, e) => {
    const { editFunction } = this.props;
    if (!editFunction) {
      message.warning("请传入修改名称用的函数");
    } else {
      editFunction(id, isLeaf, e.target.value);
    }
    this.setState({
      editingId: null,
    });
  };

  editCancel = () => {
    this.setState({
      editingId: null,
    });
  };

  onDelete = (id, isLeaf) => {
    const { deleteFunction } = this.props;
    if (deleteFunction) {
      if (isLeaf) {
        const Keys = id.split("|");
        deleteFunction(Keys[Keys.length - 1], isLeaf);
      } else {
        deleteFunction(id, isLeaf); // 可以判断isLeaf
      }
    } else {
      message.warning("请传入删除用的函数");
    }
  };

  onSelect = (selectedKeys, e) => {
    // const { selected, selectedNodes, node, event}=e
    const { treeNodeSelect } = this.props;
    // if (e.node.props.pos.split("-").length <= 2) return; // 若选中节点为租户节点，不返回节点信息
    if (treeNodeSelect) {
      if (e.node.props.isLeaf) {
        const Keys = selectedKeys[0].split("|");
        treeNodeSelect([Keys[Keys.length - 1]], e, [Keys[2]], selectedKeys); // 第一参数为当前选中ID，第三参数为父级ID，e.node.props.isLeaf 可以判断是否为叶子节点
      } else {
        treeNodeSelect(selectedKeys, e);
      }
    } else {
      message.warn("请传入函数接收目录树选择返回参数");
    }
  };

  render() {
    const {
      CatalogueData = [],
      defaultSelectedKeys = [],
      selectedKeys,
    } = this.props;
    const treeProps = { defaultSelectedKeys };
    if (selectedKeys) treeProps.selectedKeys = selectedKeys;
    return (
      <DirectoryTree
        // defaultSelectedKeys={defaultSelectedKeys}
        {...treeProps}
        onSelect={this.onSelect}
        // onExpand={onExpand}
      >
        {this.runTree(CatalogueData)}
      </DirectoryTree>
    );
  }
}

export default Catalogue;
